package com.party.jackclientandroid.api;

import android.text.TextUtils;
import android.view.View;

import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.LoginActivity;
import com.party.jackclientandroid.MApplication;
import com.party.jackclientandroid.MainActivity;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.utils.MLogUtils;

import io.reactivex.functions.Consumer;


/**
 * 默认的请求返回处理<br>
 * Created by Taxngb on 2017/12/22.
 */

public abstract class DefaultConsumer<T> implements Consumer<BaseResult<T>> {
    private static final String TAG = DefaultConsumer.class.getSimpleName();
    /**
     * 服务器操作成功的状态码
     */
    private final int successCode = 200;
    /**
     * token错误的状态码
     */
    private final int tokenErrorCode = 402;
    private MApplication mApplication;

    public DefaultConsumer(MApplication mApplication) {
        this.mApplication = mApplication;
    }

    /**
     * 后台返回操作成功调用
     *
     * @param result
     */
    public abstract void operateSuccess(BaseResult<T> result);

    /**
     * token错误的时候使用,token的优先级高于{@link #operateError(String)}
     */
    public void tokenError(String message) {
        BaseActivity topActivity = mApplication.getTopActivity();
        mApplication.cleanUser();
        DialogController.showMustConfirmDialog(topActivity, message, (View v) -> {
            topActivity.startActivity(LoginActivity.class);
        });
    }


    /**
     * 请在需要的时候打印数据
     *
     * @param message
     */
    public void operateError(String message) {
        mApplication.getTopActivity().hideAlertDialog();
        LoadViewHelper helper = mApplication.getTopActivity().helper;
        if (helper != null) helper.showError();
        if (TextUtils.isEmpty(mApplication.getToken())) ;
        mApplication.getTopActivity().showToast(message);
    }

    public void operateError(BaseResult<T> baseBean) {
        operateError(baseBean.getMessage());
    }

    @Override
    public void accept(BaseResult<T> baseBean) throws Exception {
        int code = baseBean.getCode();
        String message = baseBean.getMessage();
        if (code == successCode) {
            operateSuccess(baseBean);
        } else if (code == tokenErrorCode) {
            tokenError(message);
            MLogUtils.d(TAG, message);
        } else {
            operateError(baseBean);
        }
    }


}
